const express = require('express');
const {createServer} = require('http');
const {Server} = require('socket.io');

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
    cors: {
        origin: "*" // 生产环境应限制域名
    }
});

// 监听连接事件
io.on('connection', (socket) => {
    console.log(`客户端连接 ID: ${socket.id}`);

    // 接收客户端消息
    socket.on('chat message', (msg) => {
        console.log('收到消息:', msg);
        // 广播给所有客户端
        io.emit('chat message', msg);
    });

    // 断开连接处理
    socket.on('disconnect', () => {
        console.log('客户端断开');
    });
});

httpServer.listen(3000, () => {
    console.log('Socket.IO 服务运行在 3000 端口');
});
